import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import miniMaxService from '../services/miniMaxService';
import { v4 as uuidv4 } from 'uuid';

export const useAiChatStore = defineStore('aiChat', () => {
  // 状态
  const chatHistory = ref([]);
  const currentChatId = ref(null);
  const currentModel = ref(miniMaxService.MODELS.MINIMAX_TEXT_01);
  const isTyping = ref(false);

  // 获取当前聊天的消息
  const currentChat = computed(() => {
    if (!currentChatId.value) return null;
    return chatHistory.value.find(c => c.id === currentChatId.value);
  });

  const currentMessages = computed(() => {
    return currentChat.value ? currentChat.value.messages : [];
  });

  // 方法
  // 创建新的聊天
  const createNewChat = () => {
    const chatId = uuidv4();
    const newChat = {
      id: chatId,
      title: '新对话',
      model: currentModel.value,
      lastUpdated: new Date(),
      messages: []
    };
    
    chatHistory.value.unshift(newChat);
    currentChatId.value = chatId;
    
    // 保存到本地存储
    saveChatsToLocalStorage();
    
    return chatId;
  };

  // 选择聊天
  const selectChat = (chatId) => {
    const chat = chatHistory.value.find(c => c.id === chatId);
    if (chat) {
      currentChatId.value = chatId;
      currentModel.value = chat.model || miniMaxService.MODELS.MINIMAX_TEXT_01;
      return true;
    }
    return false;
  };

  // 选择模型
  const selectModel = (model) => {
    currentModel.value = model;
    
    // 如果当前有选中的聊天，更新其模型
    if (currentChat.value) {
      currentChat.value.model = model;
      saveChatsToLocalStorage();
    }
  };

  // 添加消息到当前聊天
  const addMessage = (content, isUser = true) => {
    if (!currentChat.value) {
      createNewChat();
    }
    
    const message = {
      id: Date.now(),
      content,
      isUser,
      timestamp: new Date()
    };
    
    currentChat.value.messages.push(message);
    currentChat.value.lastUpdated = new Date();
    
    // 如果是第一条消息，更新聊天标题
    if (currentChat.value.messages.length === 1 && isUser) {
      currentChat.value.title = content.length > 20 
        ? `${content.substring(0, 20)}...` 
        : content;
    }
    
    saveChatsToLocalStorage();
    return message;
  };

  // 删除聊天
  const deleteChat = (chatId) => {
    const index = chatHistory.value.findIndex(c => c.id === chatId);
    if (index !== -1) {
      chatHistory.value.splice(index, 1);
      
      // 如果删除的是当前选中的聊天，重置当前聊天
      if (currentChatId.value === chatId) {
        currentChatId.value = chatHistory.value.length > 0 ? chatHistory.value[0].id : null;
      }
      
      saveChatsToLocalStorage();
      return true;
    }
    return false;
  };

  // 保存聊天到本地存储
  const saveChatsToLocalStorage = () => {
    localStorage.setItem('aiChatHistory', JSON.stringify(chatHistory.value));
  };

  // 从本地存储加载聊天
  const loadChatsFromLocalStorage = () => {
    const savedChats = localStorage.getItem('aiChatHistory');
    if (savedChats) {
      try {
        chatHistory.value = JSON.parse(savedChats);
        
        // 如果有聊天记录，选择最近的一个
        if (chatHistory.value.length > 0) {
          currentChatId.value = chatHistory.value[0].id;
          currentModel.value = chatHistory.value[0].model || miniMaxService.MODELS.MINIMAX_TEXT_01;
        }
      } catch (e) {
        console.error('加载聊天历史失败:', e);
      }
    }
  };

  // 初始化 - 加载聊天历史
  loadChatsFromLocalStorage();

  return {
    // 状态
    chatHistory,
    currentChatId,
    currentModel,
    isTyping,
    currentChat,
    currentMessages,
    
    // 方法
    createNewChat,
    selectChat,
    selectModel,
    addMessage,
    deleteChat,
    saveChatsToLocalStorage,
    loadChatsFromLocalStorage
  };
}); 